package com.example.shoppingcenter.Service;

import com.example.shoppingcenter.Ai.XF.BigModel;
import com.example.shoppingcenter.Config.XFConfig;
import com.example.shoppingcenter.POJO.Chat;
import com.example.shoppingcenter.POJO.Messages;
import com.example.shoppingcenter.Mapper.xfMapper;
import com.example.shoppingcenter.POJO.Result;
import com.example.shoppingcenter.POJO.Transcript;
import jakarta.annotation.Resource;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class xfService {

    @Autowired
    private xfMapper xfMapper;
    @Autowired
    private Messages messages;
    private static boolean totalFlag = true;
    @Resource
    private XFConfig xfConfig;

    public String getAuthUrl() throws Exception {
        URL url = new URL(xfConfig.getHostUrl());
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(xfConfig.getApiSecret().getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", xfConfig.getApiKey(), "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        // System.err.println(httpUrl.toString());
        return httpUrl.toString();
    }

    public synchronized Messages getAiMessage(String userContent, Integer lastMessageId) throws Exception {
        StringBuilder historyContent = new StringBuilder();
        if (lastMessageId != -1) {
            List<Integer> parentSonList = getIntegerListInStringList(xfMapper.getMessagesById(lastMessageId).getParentSonList(), true);
            System.out.println("getAiMessage's parentSonList" + parentSonList);
            for (Integer id : parentSonList) {
                historyContent.append(xfMapper.getMessagesById(id).getUserContent()).append("/").append(xfMapper.getMessagesById(id).getModelContent()).append("/");
            }
        }
        historyContent.append(userContent);
        System.out.println("拿到的historyContent" + historyContent);

        System.out.println("Service正常");
        Messages messages = new Messages();
        String authUrl = getAuthUrl();
        OkHttpClient client = new OkHttpClient.Builder().build();
        String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
        Request request = new Request.Builder().url(url).build();
//        System.out.println(authUrl);
        BigModel bigModel = new BigModel("1", false, xfConfig);
        bigModel.setNewQuestion(historyContent.toString());
        WebSocket webSocket = client.newWebSocket(request, bigModel);
        System.out.println("发送webSocket，等一会");
        while (!bigModel.getWsCloseFlag()) {
            Thread.sleep(250);
        }

        messages.setUserContent(historyContent.toString());
        messages.setModelContent(bigModel.getTotalAnswer());
        System.out.println("拿到数据，下班");
        return messages;
    }

    public List<Chat> getChatList(Integer userId) {
        List<Chat> chat = xfMapper.getChatByUserId(userId);
        return chat;
    }


    public Result createChat(Integer userId) {
        xfMapper.createChatInUserId(userId);

        Integer chatId = xfMapper.getLastCreateChat(userId);
        xfMapper.updateChatName(chatId);
        xfMapper.createRootMessages(chatId);

        Integer root = xfMapper.getRootMessagesByChatId(chatId).getId();
        xfMapper.initRootMessages(root);
        xfMapper.updateParentSonListById(root.toString(), root);

        List<Integer> chatIdAndRoot = new ArrayList<>();
        chatIdAndRoot.add(chatId);
        chatIdAndRoot.add(root);

        System.out.println("拿到chat 的 id =" + chatId + ";" + "并且它的root节点为" + chatIdAndRoot.get(1));
        return new Result(true, chatIdAndRoot);
    }

    public Result getRootMessagesByChatId(Integer chatId) {
        Messages rootMessages = xfMapper.getRootMessagesByChatId(chatId);
        System.out.println("Server里的:" + rootMessages);
        return new Result(true, rootMessages);
    }

    public Result reloadMessagesList(Integer chatId, Integer indexId) {
        Messages thisMessage = new Messages();
        List<Integer> parentSonList = new ArrayList<>();
        List<Messages> MessagesList = new ArrayList<>();

        if (indexId == -1 || xfMapper.getTranscriptByIndexId(indexId) == null) {
            thisMessage = xfMapper.getMessagesById(xfMapper.getChatByChatId(chatId).getLastMessagesId());
            System.out.println("thisMessage:" + thisMessage);
            parentSonList = getIntegerListInStringList(thisMessage.getParentSonList(), true);
        } else {
            System.out.println("从bro中改变的:" + indexId);
            parentSonList = getIntegerListInStringList(xfMapper.getTranscriptByIndexId(indexId).getParentSonList(), true);
        }


        System.out.println("reloadMessagesList方法里的parentSonList:" + parentSonList);
        for (Integer messageId : parentSonList) {
            MessagesList.add(xfMapper.getMessagesById(messageId));
        }
        return new Result(true, MessagesList);
    }

    public void saveSonMessage(Integer chatId, String userContent, Integer lastMessageId, String modelContent) {
        System.out.println("lastMessageId is " + lastMessageId);
        saveMessage(chatId, userContent, lastMessageId, modelContent);
        Messages thisMessage = xfMapper.getLastMessagesByChatId(chatId);
        Messages lastMessage = xfMapper.getMessagesById(lastMessageId);
        System.out.println("拿出来的lastMessage和thisMessage:" + thisMessage + lastMessage);

        String parentSonList = lastMessage.getParentSonList() + "-" + thisMessage.getId().toString();
        String broIdList = thisMessage.getId().toString();
        System.out.println("parentSonList：" + parentSonList);
        xfMapper.updateParentSonListById(parentSonList, thisMessage.getId());
        xfMapper.updateBroIdListById(broIdList, thisMessage.getId());
        xfMapper.updateChatLastMessageId(thisMessage.getId(), chatId);
    }


    public void saveMessage(Integer chatId, String userContent, Integer lastMessageId, String modelContent) {
        System.out.println("正在打算存储对话Son:" + chatId + "+" + lastMessageId + "+" + userContent + "+" + modelContent + "///");
        xfMapper.saveMessageByChatId(chatId, lastMessageId, userContent, modelContent);
//        if (broMessages == null) {
//            for (Messages messages : broMessages) {
//                xfMapper.updateBroIdListById(messages.getId(), broIdList);
//            }
//        }else {
//
//        }
    }

    public List<Integer> getIntegerListInStringList(String ListString, boolean isFirst) {
        String[] splitString = ListString.split("-");
        List<Integer> parentSonList = new ArrayList<>();
        for (String str : splitString) {
            if (isFirst) {
                isFirst = false;
                continue; // 跳过第一个元素
            }
            parentSonList.add(Integer.parseInt(str));
        }
        return parentSonList;
    }

    public void saveBroMessage(Integer chatId, String userContent, Integer changedMessageId, Integer lastMessageId, String modelContent) {
        System.out.println("changedMessageId is " + changedMessageId);
        Integer changedParentMessageId = xfMapper.getMessagesById(changedMessageId).getParentId();
        saveMessage(chatId, userContent, changedParentMessageId, modelContent);
        Messages thisMessage = xfMapper.getLastMessagesByChatId(chatId);
        Messages lastMessage = xfMapper.getMessagesById(changedParentMessageId);

        String parentSonList = lastMessage.getParentSonList() + "-" + thisMessage.getId().toString();
        String broIdListString = xfMapper.getBroMessageByParentId(changedParentMessageId).get(0).getBroIdList() + "-" + thisMessage.getId().toString();
        System.out.println("同一层的BroIdList" + broIdListString);

        List<Integer> BroIdList = getIntegerListInStringList(broIdListString, false);
        System.out.println("所有的Bro" + BroIdList);
        for (Integer id : BroIdList) {
            System.out.println("遍历" + id);
            xfMapper.updateBroIdListById(broIdListString, id);
        }

        xfMapper.updateParentSonListById(parentSonList, thisMessage.getId());
        xfMapper.updateBroIdListById(broIdListString, thisMessage.getId());
        updateChatLastMessages(chatId, changedMessageId, thisMessage.getId(), lastMessageId);
    }

    public Result updateChatLastMessages(Integer chatId, Integer preId, Integer nextId, Integer lastMessageId) {
        System.out.println("updateChatLastMessages:chatId=" + chatId + "/preId=" + preId + "/nextId=" + nextId + "/lastMessageId=" + lastMessageId);
        Messages lastMessage = xfMapper.getMessagesById(lastMessageId);
        List<Integer> parentSonList = new ArrayList<>();
        if (xfMapper.getTranscriptByIndexId(preId) == null) {
            xfMapper.initTranscript(preId, chatId, lastMessage.getParentSonList());
        } else {
            xfMapper.updateTranscriptByIndexId(preId, lastMessage.getParentSonList());
        }
        Transcript transcript = xfMapper.getTranscriptByIndexId(nextId);
        if (transcript != null) {
            parentSonList = getIntegerListInStringList(transcript.getParentSonList(), true);
            System.out.println("parentSonList last is:" + parentSonList.get(parentSonList.size() - 1));
            xfMapper.updateChatLastMessageId(parentSonList.get(parentSonList.size() - 1), chatId);
//            xfMapper.updateChatLastMessageId(nextId, chatId);
        } else {
            xfMapper.updateChatLastMessageId(nextId, chatId);
        }
//        System.out.println(xfMapper.getLastMessagesByChatId(chatId));
        return new Result();
    }

    public Result deleteChat(Integer chatId) {
        System.out.println("deleteChat's Server:" + chatId  );
        xfMapper.deleteChatTranscript(chatId);
        xfMapper.deleteChatMessage(chatId);
        xfMapper.deleteChat(chatId);
        return new Result();
    }
}

